package com.iflytek.iot.platform.tracing.config;

import com.iflytek.drip.log.loglib.config.HostInfo;
import com.iflytek.drip.log.loglib.utils.FlumeException;
import com.iflytek.iot.common.utils.RandomUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

public class HostInfoConfig {

    public static List<HostInfo> getHostInfo(String flumeAgent){
        String hostString = flumeAgent;

        List<HostInfo> hostsList = new ArrayList();
        String[] hostsString = hostString.split(" ");

        for(int i = 0; i < hostsString.length; ++i) {
            String[] tmps = hostsString[i].split(":");
            if (tmps.length != 2 && tmps.length != 3) {
                throw new FlumeException("error flume agent config");
            }

            HostInfo curHostInfo = null;
            if (tmps.length == 3) {
                curHostInfo = new HostInfo(hostsString[i], tmps[0], Integer.parseInt(tmps[1]), Integer.parseInt(tmps[2]));
            } else {
                curHostInfo = new HostInfo(hostsString[i], tmps[0], Integer.parseInt(tmps[1]), Integer.parseInt("1"));
            }

            if (contains(hostsList, curHostInfo)) {
                hostsList.get(position(hostsList, curHostInfo)).addWeight(curHostInfo.getHostWeight());
            } else {
                hostsList.add(curHostInfo);
            }
        }
        return hostsList;
    }

    private static boolean contains(List<HostInfo> list, HostInfo host) {
        boolean ret = false;
        Iterator i$ = list.iterator();

        while(i$.hasNext()) {
            HostInfo hostInfo = (HostInfo)i$.next();
            if (hostInfo.identity().equals(host.identity())) {
                ret = true;
            }
        }

        return ret;
    }

    private static int position(List<HostInfo> list, HostInfo host) {
        int ret = 0;

        for(int i = 0; i < list.size(); ++i) {
            if (((HostInfo)list.get(i)).identity().equals(host.identity())) {
                ret = i;
            }
        }

        return ret;
    }

    public static void main(String[] args){
        Random random = new Random();

        List<HostInfo> hostInfos = getHostInfo("10.236.64.123:32000 10.236.64.124:32000 10.236.64.125:32000 10.236.64.126:32000");
//        int n = RandomUtils.randomInt(0, 5);
        for (int i = 0; i < 100; i++) {
            System.out.println(RandomUtils.randomInt(0, hostInfos.size()));
//            System.out.println(JSON.toJSONString(hostInfos.get(n)));
        }
    }

}
